// pages/group/groupDetail.js
import { $wuxCountDown } from '../../components/wux/index.js'
import groupApi from '../../service/groupApi.js'
import { reLogin } from '../../service/request'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    groupId: '',
    hours: '00',
    min: '00',
    sec: '00',
    inviteTips: '', // 未参团时的提示
    showGroupRules: false,
    hadAuthFlag: false, // 是否授权
    getCouponFlag: false, // 是否领取了优惠券
    btnText: '立即参团',
    groupInfo: {
      orderInfo: {},
      couponInfo: {},
      groupInfoList: []
    },
    loading: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.groupId) {
      this.setData({
        groupId: options.groupId
      })
      this.checkStatus()
    }
  },
  initData () {
    let that = this
    this.getInitData(that.data.groupId).then(res => {
      this.setData({
        groupInfo: res.data,
        loading: false
      })
      if (!res.data.grouperFlag) {
        if (res.data.groupStatus === '0') {
          this.setData({
            inviteTips: res.data.groupLeaderName + '送你一张拼团券，邀请你一起拼团买好物！'
          })
        } else if (res.data.groupStatus === '1') {
          this.setData({
            inviteTips: res.data.groupLeaderName + '发起的拼团已满员，TA送你一张拼团券，快去发起拼团吧！'
          })
        } else if (res.data.groupStatus === '2') {
          this.setData({
            inviteTips: res.data.groupLeaderName + '发起的拼团已到期，TA送你一张拼团券，快去发起拼团吧！'
          })
        }
      }
      if (res.data.groupStatus === '0') {
        this.initTimer(res.data.expireTime)
      }
    })
  },
  // 授权状态的检查
  checkStatus () {
    let that = this
    // 判断是否有授权，有授权的话从回调调用方法初始化数据
    // 无授权的话直接调用方法初始化数据
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          that.setData({
            hadAuthFlag: true,
            getCouponFlag: true,
            btnText: '立即参团'
          })
          if (wx.getStorageSync('token')) {
            that.initData()
          } else {
            app.checkStatusCallback = res => {
              that.setData({
                userInfo: res,
                hasUserInfo: true
              })
              that.initData()
            }
          }
        } else {
          that.initData()
          that.setData({
            btnText: '立即领取'
          })
        }
      }
    })
  },
  // 获取用户信息回调
  bindGetUserInfo (e) {
    let that = this
    // that.showConfrimLoading()
    console.log(e)
    let btnType = e.currentTarget.dataset.type
    if (!!e.detail.userInfo) { // 同意授权-并登陆
      wx.setStorageSync('hadAuthFlag', true)
      app.globalData.userInfo = e.detail.userInfo
      app.globalData.hadAuthUserInfo = true
      wx.showLoading({
        icon: 'none',
        title: '登录中...'
      })
      reLogin().then(() => {
        wx.hideLoading()
        that.setData({
          hadAuthFlag: true
        })
        if (btnType === 'GET_COUPON') {
          that.handleGetGroupCoupon()
        } else if (btnType === 'START_GROUP') {
          that.goBuy()
        } 
      }).catch((res) => {
        wx.hideLoading()
        // that.hideConfrimLoading()
      })
    } else { // 不同意授权
      // that.hideConfrimLoading()
      wx.setStorageSync('hadAuthFlag', false)
      that.setData({
        hadAuthFlag: false
      })
    }
  },
  closeRulePup () {
    this.setData({
      showGroupRules: false
    })
  },
  openRulePup () {
    this.setData({
      showGroupRules: true
    })
  },
  goBuy () {
    app.globalData.refreshIndexFlag = true
    wx.reLaunch({
    	url: '../index/index'
    })
  },
  joinNow () {
    app.globalData.refreshIndexFlag = true
    app.globalData.groupId = this.data.groupId
    wx.reLaunch({
    	url: '../index/index'
    })
  },
  goGoodsDetail (e) {
    console.log(e.currentTarget.dataset.goodsid)
    wx.navigateTo({
    	url:'../goodsDetail/goodsDetail?goodsId=' + e.currentTarget.dataset.goodsid
    })
  },
  initTimer (timer) {
    this.countDownTimer = new $wuxCountDown({
      date: timer,
      render (date) {
        this.setData({
          hours: this.leadingZeros(date.hours, 2),
          min: this.leadingZeros(date.min, 2),
          sec: this.leadingZeros(date.sec, 2)
        })
      },
      onEnd () {
        console.log('倒计时结束！！')
        this.setData({
          hours: '00',
          min: '00',
          sec: '00',
          'groupInfo.groupStatus': '2'
        })
      }
    })
  },
  getInitData (groupId) {
    return new Promise((resolve, reject) => {
      groupApi.getGroupDetail({
        groupId
      }).then(res => {
        console.log(res)
        if (res.data.errCode === app.globalData.codeConfig.errCode.SUCCESS_CODE) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      })
    })
  },
  handleGetGroupCoupon () {
    let that = this
    wx.showLoading({
      icon: 'none',
      title: '领取中'
    })
    groupApi.getGroupCoupon({
      groupId: that.data.groupId
    }).then((res) => {
      wx.hideLoading()
      if (res.data.errCode === app.globalData.codeConfig.errCode.SUCCESS_CODE) {
        that.setData({
          getCouponFlag: true
        })
        wx.showToast({
          icon: 'none',
          title: '领取成功，快去参团吧'
        })
      } else {
        that.setData({
          getCouponFlag: false
        })
        wx.showToast({
          icon: 'none',
          title: res.data.msg
        })
      }
    }).catch((err) => {
      that.setData({
        getCouponFlag: false
      })
      wx.hideLoading()
      wx.showToast({
        icon: 'none',
        title: '网络不给力，请稍后再试'
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    return {
      imageUrl: app.globalData.picBaseUrl + '/group/20190507/CeX4L1XxoTIL.png',
      title: app.globalData.userInfo.nickName + '邀请你参加TA的拼团，全场商品8折任意拼。',
      path: '/pages/group/groupDetail?groupId=' + this.data.groupId
    }
  }
})